from pypylon import pylon
import cv2
import datetime
import time
import os


def search_get_device():
    i = 0
    tl_factory = pylon.TlFactory.GetInstance()
    for dev_info in tl_factory.EnumerateDevices():
        print("DeviceClass:", dev_info.GetDeviceClass())
        if dev_info.GetDeviceClass() == 'BaslerGigE':  # 千兆网(GigE)
            if i == 0:
                print(f"ModelName:{dev_info.GetModelName()}\n"f"IP:{dev_info.GetIpAddress()}")
                camera = pylon.InstantCamera(tl_factory.CreateDevice(dev_info))
                i += 1
            elif i == 1:
                print(f"ModelName:{dev_info.GetModelName()}\n"f"IP:{dev_info.GetIpAddress()}")
                camera1 = pylon.InstantCamera(tl_factory.CreateDevice(dev_info))
                break
    else:
        raise EnvironmentError("no GigE device found")

    return camera, camera1


camera, camera1 = search_get_device()
camera.Open()  # 将相机打开
camera1.Open()

# 以最小延迟连续抓取(视频)
camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
converter = pylon.ImageFormatConverter()
camera1.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
converter1 = pylon.ImageFormatConverter()
# 转换为opencv BGR格式
converter.OutputPixelFormat = pylon.PixelType_BGR8packed  # 如果需要转换成RBG格式，改为PixelType_RBG8packed
converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned
converter1.OutputPixelFormat = pylon.PixelType_BGR8packed  # 如果需要转换成RBG格式，改为PixelType_RBG8packed
converter1.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned
# 等待一个图像，然后检索它。超时时间为5000ms。
grabResult = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)
grabResult1 = camera1.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)

i = 50
while camera.IsGrabbing() or camera1.IsGrabbing():
    grabResult = camera.RetrieveResult(1000, pylon.TimeoutHandling_ThrowException)
    grabResult1 = camera1.RetrieveResult(1000, pylon.TimeoutHandling_ThrowException)

    if grabResult.GrabSucceeded():
        # Access the image data
        image = converter.Convert(grabResult)
        imgR = image.GetArray()
        cv2.namedWindow("cameraL", cv2.WINDOW_NORMAL)
        cv2.imshow("cameraL", imgR)
        # # 连续输出图像路径，按数字顺序给图像命名
        cv2.imwrite('L' + str(i) + '.bmp', imgR)
        # i = i + 1
        # # 每隔0.025秒采集一张图像
        # time.sleep(5)

        cv2.waitKey(300)

    if grabResult1.GrabSucceeded():
        # Access the image data
        imageL = converter.Convert(grabResult1)
        imgL = imageL.GetArray()
        cv2.namedWindow("cameraR", cv2.WINDOW_NORMAL)
        cv2.imshow("cameraR", imgL)
        cv2.imwrite('R' + str(i) + '.bmp', imgL)
        # i = i + 1
        cv2.waitKey(300)

        k = cv2.waitKey(30)

        if k == 27:
            cv2.destroyAllWindows()
            break

    grabResult.Release()
    grabResult1.Release()
# Releasing the resource
camera.StopGrabbing()
camera1.StopGrabbing()

cv2.destroyAllWindows()

# if key & 0xFF == ord('s'):  # 按S同时保存左右图像
#     savePath_L = os.path.join(self.savepath_L, "L{:0>3d}.png".format(num))
#     print(savePath_L)
#     cv2.imwrite(savePath_L, self.img_l)
#     savePath_R = os.path.join(self.savepath_R, "R{:0>3d}.png".format(num))
#     cv2.imwrite(savePath_R, self.img_r)
#     num += 1
# if key & 0xFF == 27:  # 按esc退出视图窗口
#     break
